package com.hx.voice.recognition.auth.client.jwt;

import com.hx.voice.recognition.auth.client.config.ServiceAuthConfig;
import com.hx.voice.recognition.auth.client.feign.ServiceAuthFeign;
import com.hx.voice.recognition.auth.common.util.jwt.IJWTInfo;
import com.hx.voice.recognition.auth.common.util.jwt.JWTHelper;
import com.hx.voice.recognition.common.exception.auth.ClientTokenException;
import com.hx.voice.recognition.common.msg.BaseResponse;
import com.hx.voice.recognition.common.msg.ObjectRestResponse;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @descripe：应用授权工具
 * @company：南京华讯方舟通讯设备有限公司
 * @author：zhoujinbing
 * @time：2019/6/11 10:34
 * @version：V1.0
 */
@Configuration
@Slf4j
@EnableScheduling
public class ServiceAuthUtil {

    /**
     * 应用授权配置
     */
    @Autowired
    private ServiceAuthConfig serviceAuthConfig;

    /**
     * feign调用授权服务端
     */
    @Autowired
    private ServiceAuthFeign serviceAuthFeign;

    private List<String> allowedClient;
    private String clientToken;

    /**
     * @description 根据token获取jwt鉴权信息
     * @method  getInfoFormToken
     * @param  [token]
     * @return IJWTInfo
     * @date: 2019/6/11 11:15
     * @author:zhoujinbing
     */
    public IJWTInfo getInfoFormToken(String token) throws Exception
    {
        try {
            return JWTHelper.getInfoFormToken(token,serviceAuthConfig.getPubKeyByte());
        }catch (ExpiredJwtException ex)
        {
            throw new ClientTokenException("Client token expired!");
        }catch (SignatureException ex)
        {
            throw new ClientTokenException("Client token signature error!");
        }catch (IllegalArgumentException ex)
        {
            throw  new ClientTokenException("Client token is null or empty!");
        }
    }

    /**
     * @description 定时维护可以被允许调用的应用
     * @method  refreshAllowedClient
     * @param  []
     * @return void
     * @date: 2019/6/20 10:42
     * @author:zhoujinbing
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void refreshAllowedClient()
    {
        log.debug("refresh allowedClient.....");
        BaseResponse resp = serviceAuthFeign.getAllowClient(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
        if (resp.getStatus() == 200) {
            ObjectRestResponse<List<String>> allowedClient = (ObjectRestResponse<List<String>>) resp;
            this.allowedClient = allowedClient.getData();
        }
    }

    /**
     * @description 定时刷新应用token
     * @method  refreshClientToken
     * @param  []
     * @return void
     * @date: 2019/6/20 10:42
     * @author:zhoujinbing
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void refreshClientToken()
    {
        log.debug("refresh client token");
        BaseResponse resp = serviceAuthFeign.getAccessToken(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
        if (resp.getStatus() == 200) {
            ObjectRestResponse<String> clientToken = (ObjectRestResponse<String>) resp;
            this.clientToken = clientToken.getData();
        }

    }

    public String getClientToken()
    {
        if(this.clientToken == null )
        {
            refreshClientToken();
        }
        return clientToken;
    }

    public List<String> getAllowedClient()
    {
        if (allowedClient == null)
        {
            refreshAllowedClient();
        }
        return allowedClient;
    }








}